package cc.comac.mom.util;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.google.common.collect.Maps;

public class BeanManager implements ApplicationContextAware{
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		BeanManager.applicationContext = applicationContext;
	}

	// 获得applicationContext
	public static ApplicationContext getApplicationContext() {
		// assertContextInjected();
		return applicationContext;
	}

	public static void clearHolder() {
		applicationContext = null;
	}

	//获取Bean
	@SuppressWarnings("hiding")
	public static <T> T getBean(Class<T> requiredType) {
		// assertContextInjected();
		return  applicationContext.getBean(requiredType);
	}
	
	public static  <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }
	
	public static  <T> Map<String, String> beanToStringMap(T bean) {
        Map<String, String> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key.toString() + "", beanMap.get(key).toString());
            }
        }
        return map;
    }

}
